package com.xique.park.controller.mini;

import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IWxGzhApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: caogq
 * @Date: 2022/8/3 11:58
 * @Description:
 */
@RestController
@RequestMapping("wx")
@Slf4j
public class WxParkController {

    @Value("${wx.gzh.appid}")
    private String gzhAppid;

    @Value("${wx.gzh.secret}")
    private String gzhSecret;

    @Autowired
    private IWxGzhApi wxGzhApi;

    @GetMapping("/getGzhOpenId")
    public AjaxResult getGzhOpenId(String code){
        Map<String, Object> params = new HashMap<>(4);
        params.put("appid", gzhAppid);
        params.put("secret", gzhSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        JSONObject result = wxGzhApi.getAccessToken(params);
        Object openid = result.get("openid");
        if (Objects.isNull(openid)){
            log.error("获取用户信息失败,返回消息：{}",result.get("errmsg").toString());
            return AjaxResult.error("获取用户信息失败，请联系管理员！");
        }
        log.info("前端获取code：{}，后端返回openid: {}",code,openid);
        return AjaxResult.success(Collections.singletonMap("openid",openid.toString()));
    }
}
